package nancal.mp.web.me

import nancal.mp.db.mongo.UserPartnerTypeEnum
import nancal.mp.db.mongo.entity.shop.PartnerConfig
import nancal.mp.db.mongo.mor
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.db.IdUrl
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.update
import nbcp.myoql.db.mongo.updateById
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDateTime

/**
 * 相册列表 内部  CRUD
 */
@RestController
@RequestMapping("/partner")
class Partner_Controller {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @PostMapping("/config")
    fun list(): ListResult<PartnerConfig> {
        return mor.shop.partnerConfig.query().toListResult()
    }


    @PostMapping("save")
    fun save(
            id: String,
            type: UserPartnerTypeEnum,
            remark: String,
            commission: Int
    ): JsonResult {

        mor.shop.partnerConfig.updateById(id)
                .set { it.remark to remark }
                .set { it.commission to commission }
                .set { it.updateAt to LocalDateTime.now() }
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult.error("保存失败或没有修改")
        }

        mor.wx.wxAppUser.update()
                .where { it.partnerType mongoEquals type }
                .set { it.commission to commission }
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult.error("更新用户分成比例错误")
        }

        return JsonResult()
    }


    /**
     * 设置背景图片
     */
    @PostMapping("setBanner")
    fun setBanner(
            id:String,
            banner: IdUrl
    ):JsonResult{

        mor.shop.partnerConfig.updateById(id)
                .set { it.banner to banner }
                .exec()

        return JsonResult()
    }


}
